package org.tong.order.service;

import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tong.account.AccountServiceI;
import org.tong.order.jpa.OrderJpaRepository;
import org.tong.order.jpa.OrderTccDaoI;
import org.tong.order.jpa.beans.Order;

import java.util.Random;

/**
 * @author
 * @date 2022-12-21 16:37
 */
@Service
public class OrderService {

    @Autowired
    private AccountServiceI accountServiceI;

    @Autowired
    private OrderJpaRepository orderJpaRepository;

    @Autowired
    private OrderTccDaoI orderTccDaoI;

    @GlobalTransactional
    public void addOrderAndAccount(Long id, String name) {
        Order order = new Order();
        order.setId(id);
        order.setName(name);
        order.setCreateTime(System.currentTimeMillis());
        orderJpaRepository.save(order);
        accountServiceI.addAccount(id, name);
    }

    @GlobalTransactional(timeoutMills = 5000)
    public void addAmountByTcc(Long id, Long amount) {
        // 本服务的方法
        {
            orderTccDaoI.prepare(null, id, amount);
        }
        // 远程方法
        accountServiceI.addAmount(id, amount);


        int randomFlg = new Random().nextInt(10);
        System.out.println("sleep " + randomFlg + "s");
        try {
            Thread.sleep(1000 * randomFlg);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
